import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { findSubCategoryFilter } from '@/api/category'
export function useFilterData () {
  const subObj = ref({})
  const keyWord = ref([])
  const route = useRoute()

  onMounted(async () => {
    const res = await findSubCategoryFilter(route.params.id)
    subObj.value = res.result

    // 遍历添加全部标识
    subObj.value.saleProperties.forEach((item) => {
      item.properties.unshift({
        id: null,
        name: '全部'

      })
    })

    // 遍历添加布尔值
    subObj.value.saleProperties.forEach((item) => {
      item.properties.forEach((k) => {
        if (k.id === null) {
          k.flag = true
        } else {
          k.flag = false
        }
      })
    })
  })

  function toggleFn (list, target, parentName) {
    // 排他思想，干掉所有人
    list.forEach((item) => {
      item.flag = false
    })

    // 只剩我自己
    target.flag = true

    const index = keyWord.value.findIndex((item) => item.groupName === parentName)
    if (index >= 0) {
      keyWord.value.splice(index, 1)
    }

    if (target.name !== '全部') {
      keyWord.value.push({
        groupName: parentName,
        propertyName: target.name
      })
    }
  }

  return {
    subObj,
    toggleFn,
    keyWord
  }
}
